<?php
/**
 * @Name: WechatAuthorization.php
 * @Author: yashuai<1762910894@qq.com>
 * @desc 网页授权开发
 */

namespace App\Http\Controllers;

use App\Http\Services\AccessTokenServices;
use HugCode\WeChat\Offiaccount\OAWebApps\Authorization;

class WechatAuthorization
{

    /**
     * @Desc 获取微信授权跳转地址
     * @author yashuai<1762910894@qq.com>
     */
    public function login(Request $request)
    {
        $params = $request->all();
        $config = AccessTokenServices::getAccessToken();
        try {
            $state    = $params['state'] ?: '';
            $callback = 'callback';
            $url      = (new Authorization($config))->getOauthRedirect($callback, $state);
            $this->location($url);
        } catch (\Exception $e) {
            $domain = env('WAP_HOST');
            $this->location($domain . 'error?title=登录失败&msg=' . $e->getMessage());
        }
    }

    /**
     * @Desc 获取微信授权用户信息
     * @author yashuai<1762910894@qq.com>
     */
    private function callback()
    {
        $domain = env('WAP_HOST');
        try {
            $config = AccessTokenServices::getConfig();
            $wechat = new Authorization($config);
            $oauth  = $wechat->getOauthAccessToken();
            $openid = $oauth['openid'] ?: false;
            if (empty($openid)) {
                $this->location($domain . 'error?title=登录失败&msg=open_id获取失败');
            }
            return $wechat->getUserInfo($oauth['access_token'], $openid);
        } catch (\Exception $e) {
            $this->location($domain . 'error?title=登录失败&msg=' . $e->getMessage());
        }
    }

    public function location(string $url = '')
    {
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $url);
        exit;
    }

}
